package com.hzcx.app.simplechat.ui.login;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.base.BaseActivity;
import com.hzcx.app.simplechat.common.Common;
import com.hzcx.app.simplechat.common.CommonSp;
import com.hzcx.app.simplechat.ui.login.bean.AliLoginResultBean;
import com.hzcx.app.simplechat.ui.login.bean.DomainNameBean;
import com.hzcx.app.simplechat.ui.login.bean.LoginInfoBean;
import com.hzcx.app.simplechat.ui.login.contract.LoginContract;
import com.hzcx.app.simplechat.ui.login.event.PhoneCityEvent;
import com.hzcx.app.simplechat.ui.login.event.WxLoginSuccessEvent;
import com.hzcx.app.simplechat.ui.login.presenter.LoginPresenter;
import com.hzcx.app.simplechat.ui.login.util.LoginUtil;
import com.hzcx.app.simplechat.ui.publicui.PrivacyActivity;
import com.hzcx.app.simplechat.ui.publicui.SendCodeActivity;
import com.hzcx.app.simplechat.ui.publicui.ShareActivity;
import com.hzcx.app.simplechat.ui.publicui.WebViewActivity;
import com.hzcx.app.simplechat.ui.publicui.bean.ProtocolBean;
import com.hzcx.app.simplechat.ui.publicui.enums.SendCodeEnum;
import com.hzcx.app.simplechat.util.app.AppHelper;
import com.hzcx.app.simplechat.util.dp.DpUtils;
import com.hzcx.app.simplechat.util.empty.EmptyUtils;
import com.hzcx.app.simplechat.util.log.LogUtils;
import com.hzcx.app.simplechat.util.map.GdMapUtils;
import com.hzcx.app.simplechat.util.net.NetWorkUtils;
import com.hzcx.app.simplechat.util.sp.SPUtils;
import com.hzcx.app.simplechat.util.toast.ToastUtils;
import com.hzcx.app.simplechat.view.MainBlueConfirmButton;
import com.mobile.auth.gatewayauth.AuthRegisterXmlConfig;
import com.mobile.auth.gatewayauth.AuthUIConfig;
import com.mobile.auth.gatewayauth.PhoneNumberAuthHelper;
import com.mobile.auth.gatewayauth.TokenResultListener;
import com.mobile.auth.gatewayauth.model.TokenRet;
import com.mobile.auth.gatewayauth.ui.AbstractPnsViewDelegate;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

/**
 * 登录首页
 */
public class LoginActivity extends BaseActivity<LoginPresenter> implements LoginContract.View {

    public static final String INTENT_TAG_KICKOUT = "INTENT_TAG_KICKOUT";

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_tips)
    TextView tvTips;
    @BindView(R.id.ll_phone)
    LinearLayout llPhone;
    @BindView(R.id.btn_login)
    MainBlueConfirmButton btnLogin;
    @BindView(R.id.tv_agreement_user)
    TextView tvAgreementUser;
    @BindView(R.id.tv_agreement_private)
    TextView tvAgreementPrivate;
    @BindView(R.id.ll_agreement)
    LinearLayout llAgreement;
    @BindView(R.id.iv_login_wx)
    ImageView ivLoginWx;
    @BindView(R.id.iv_login_qq)
    ImageView ivLoginQq;
    @BindView(R.id.ll_login_other)
    LinearLayout llLoginOther;
    @BindView(R.id.iv_agreement)
    ImageView ivAgreement;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.tv_phone_city)
    TextView tvPhoneCity;
    @BindView(R.id.tv_login_by_phone)
    TextView tvLoginByPhone;

    private boolean isAgreement = true;

    private TokenResultListener mTokenListener;
    private PhoneNumberAuthHelper mAlicomAuthHelper;
    private AuthRegisterXmlConfig xmlConfig;

    private IWXAPI api;
    private int tag;
    private LoginInfoBean loginInfoBean;
    private int premissionTag = 0;

    @Override
    public int getLayout() {
        return R.layout.activity_login;
    }

    @Override
    public void initPresenter() {
        mPresenter = new LoginPresenter();
    }

    @Override
    public void initView() {
        btnLogin.setEditText(etPhone, 11);

        if (NetWorkUtils.isMobileDataEnabled(this)) {
            tvLoginByPhone.setVisibility(View.VISIBLE);
        } else {
            tvLoginByPhone.setVisibility(View.GONE);
        }
        boolean loginFirst = SPUtils.getBoolean(CommonSp.LOGIN_FIRST);
        if (loginFirst){
            btnLogin.postDelayed(new Runnable() {
                @Override
                public void run() {
                    startActivity(new Intent(LoginActivity.this, PrivacyActivity.class));
                }
            },1000);
        }

    }

    @Override
    public void initData() {
        if (getIntent().getBooleanExtra(INTENT_TAG_KICKOUT, false)) {
            showTips("提示", "您的账号已在其他地方登陆，如非本人操作，请尽快修改密码", null);
        }

        registerLocationPermission();

        mPresenter.getDomainNameConfig(this);
    }

    @OnClick({R.id.btn_login, R.id.iv_agreement, R.id.iv_login_qq, R.id.tv_phone_city, R.id.tv_login_by_phone, R.id.iv_login_wx
            , R.id.tv_agreement_user, R.id.tv_agreement_private})
    public void viewOnClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login: // 登录
                login();
                break;

            case R.id.iv_agreement: // 协议按钮
                if (isAgreement) {
                    ivAgreement.setImageResource(R.mipmap.ic_icon_radio_normal);
                } else {
                    ivAgreement.setImageResource(R.mipmap.ic_icon_radio_selete);
                }
                isAgreement = !isAgreement;
                break;

            case R.id.tv_phone_city: // 选择号码地区
                startActivity(new Intent(this, PhoneCityActivity.class));
                break;

            case R.id.tv_login_by_phone: // 一键登录
                tag = 0;
                premissionTag = 1;
                registerPermission();
                break;

            case R.id.iv_login_wx: // 微信登录
                wxLogin();
                break;

            case R.id.iv_login_qq: // QQ登录
                showError("暂不支持QQ登录");
                break;

            case R.id.tv_agreement_user: // 用户协议
                mPresenter.getProtocol(this, "agreement");
                break;

            case R.id.tv_agreement_private: // 隐私政策
                mPresenter.getProtocol(this, "policy");
                break;
        }
    }

    /**
     * 登录
     */
    private void login() {
        if (!isAgreement) {
            showError("请先同意用户协议和隐私协议");
            return;
        }
        mPresenter.getUserIsRegister(this, etPhone.getText().toString(), tvPhoneCity.getText().toString(), AppHelper.getDeviceBrand());
    }


    /**
     * 选择手机号地区返回
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void phoneCityChange(PhoneCityEvent event) {
        tvPhoneCity.setText(event.getBean().getPrefix());
    }

    /**
     * 获取权限
     */
    private void registerPermission() {
        PermissionGen.with(this)
                .addRequestCode(Common.BASIC_PERMISSION_REQUEST_CODE)
                .permissions(Manifest.permission.WRITE_EXTERNAL_STORAGE
                        , Manifest.permission.READ_EXTERNAL_STORAGE
                        , Manifest.permission.READ_PHONE_STATE)
                .request();
    }

    /**
     * 获取位置权限
     */
    private void registerLocationPermission() {
        PermissionGen.with(this)
                .addRequestCode(Common.BASIC_PERMISSION_REQUEST_CODE)
                .permissions(Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.READ_PHONE_STATE)
                .request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @PermissionFail(requestCode = Common.BASIC_PERMISSION_REQUEST_CODE)
    public void openFail() {
        ToastUtils.show("权限获取失败,请先设置权限");
    }

    /**
     * 权限申请成功
     */
    @PermissionSuccess(requestCode = Common.BASIC_PERMISSION_REQUEST_CODE)
    public void openSuccess() {
        if (premissionTag == 1) {
            showAliLoginUi(tag);
        } else {
            GdMapUtils.getInstance().startLocation(new AMapLocationListener() {
                @Override
                public void onLocationChanged(AMapLocation aMapLocation) {
                    if (aMapLocation.getErrorCode() != 0) {
                        LogUtils.d("定位失败");
                        return;
                    }
                    LogUtils.d("定位地址：" + aMapLocation.getAddress());
                }
            });
        }
    }

    /**
     * 阿里云一键登录界面
     */
    private void showAliLoginUi(int tag) {
        if (mAlicomAuthHelper != null) {
            mAlicomAuthHelper.removeAuthRegisterXmlConfig();
        }
        // 阿里云一键登录
        mTokenListener = new TokenResultListener() {
            @Override
            public void onTokenSuccess(String s) {
                //token获取成功
                TokenRet tokenRet = null;
                String token = null;
                try {
                    tokenRet = JSON.parseObject(s, TokenRet.class);
                } catch (Exception e) {
                    e.printStackTrace();
                    hideLoading();
                    mAlicomAuthHelper.hideLoginLoading();
                    runOnUiThread(() -> showError("无法获取到手机号，请手动输入登录"));
                }
                if (tokenRet != null && ("600000").equals(tokenRet.getCode())) {
                    token = tokenRet.getToken();
                    mAlicomAuthHelper.quitLoginPage();
                    LogUtils.d(TAG, "token:" + token);
                    if (EmptyUtils.isNotEmpty(token)) {
                        hideLoading();
                        mAlicomAuthHelper.hideLoginLoading();
                        if (tag == 1) {
                            // tag为1表示绑定手机号验证，而不是一键登录
                            mPresenter.bindPhoneByAli(LoginActivity.this, loginInfoBean.getToken(), token);
                        } else {
                            mPresenter.loginByAli(LoginActivity.this, token, AppHelper.getDeviceBrand());
                        }
                    } else {
                        hideLoading();
                        mAlicomAuthHelper.hideLoginLoading();
                        runOnUiThread(() -> showError("无法获取到手机号，请手动输入登录"));
                    }
                }
            }

            @Override
            public void onTokenFailed(String s) {
                // token获取失败，到手机号输入界面
                LogUtils.e(TAG, s);
                if (tag == 1) {
                    startActivity(new Intent(LoginActivity.this, BindPhoneActivity.class)
                            .putExtra(BindPhoneActivity.INTENT_LOGIN_INFO, loginInfoBean));
                    return;
                }
                AliLoginResultBean bean = new Gson().fromJson(s, AliLoginResultBean.class);
                hideLoading();
                mAlicomAuthHelper.hideLoginLoading();
                if (!bean.getCode().equals("700000") && !bean.getCode().equals("700001")) {
                    runOnUiThread(() -> showError("无法获取到手机号，请手动输入登录"));
                }
            }
        };
        // 调用一键登录
        setAliLoginView(tag);
        mAlicomAuthHelper.setAuthListener(mTokenListener);
        mAlicomAuthHelper.setAuthSDKInfo(Common.ALI_LOGIN_KEY);
        /*
         *   使用一键登录传入 SERVICE_TYPE_LOGIN
         *   使用号码校验传入 SERVICE_TYPE_AUTH
         */
        mAlicomAuthHelper.checkEnvAvailable(2);
        mAlicomAuthHelper.getLoginToken(this, 5000);
        showLoading();
    }

    /**
     * 设置阿里云一键登录UI
     */
    private void setAliLoginView(int tag) {
        mAlicomAuthHelper = PhoneNumberAuthHelper.getInstance(this, mTokenListener);
        mAlicomAuthHelper.setAuthUIConfig(new AuthUIConfig.Builder()
                .setNavHidden(true)
                .setNavReturnHidden(true)
                .setLightColor(true)
                .setSloganText("未注册手机号登录后将自动创建账号")
                .setSloganTextColor(getResources().getColor(R.color.color_A6A8B0))
                .setSloganTextSize(DpUtils.dp2px(this, 5))
                .setSloganOffsetY(DpUtils.dp2px(this, 85))
                .setNumFieldOffsetY(DpUtils.dp2px(this, 70))
                .setLogBtnOffsetY(DpUtils.dp2px(this, 110))
                .setSwitchOffsetY(DpUtils.dp2px(this, 140))
                .setSwitchAccText(tag == 1 ? "切换账号" : "短信或密码登录")
                .setSwitchAccTextColor(getResources().getColor(R.color.color_A6A8B0))
                .setSwitchAccTextSize(DpUtils.dp2px(this, 5))
                .setLogBtnText(tag == 1 ? "一键验证" : "一键登录")
                .setPrivacyState(true)
                .create());

        if (tag == 0) {
            mAlicomAuthHelper.addAuthRegisterXmlConfig(new AuthRegisterXmlConfig.Builder()
                    .setLayout(R.layout.layout_login_ali_bottom, new AbstractPnsViewDelegate() {
                        @Override
                        public void onViewCreated(View view) {
                            findViewById(R.id.iv_login_wx).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    mAlicomAuthHelper.quitLoginPage();
                                    wxLogin();
                                }
                            });

                            findViewById(R.id.iv_login_qq).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    mAlicomAuthHelper.quitLoginPage();
                                    showError("暂不支持QQ登录");
                                }
                            });
                        }
                    })
                    .build());
        }
    }

    /**
     * 登录成功
     *
     * @param data
     */
    @Override
    public void loginSuccess(LoginInfoBean data, int tag) {
        hideLoading();
        this.loginInfoBean = data;
        if (tag == 2) {
            // 微信登录，判断是否需要绑定手机号
            if (EmptyUtils.isEmpty(data.getMobile())) {
                this.tag = 1;
                registerPermission();
            } else {
                LoginUtil.loginSuccess(this, data);
            }
        } else {
            LoginUtil.loginSuccess(this, data);
        }
    }

    /**
     * 手机号绑定成功
     */
    @Override
    public void bindSuccess() {
        LoginUtil.loginSuccess(this, loginInfoBean);
    }

    /**
     * 协议内容获取成功
     *
     * @param data
     */
    @Override
    public void protocolResult(ProtocolBean data) {
        startActivity(new Intent(this, WebViewActivity.class)
                .putExtra(WebViewActivity.INTENT_TITLE, data.getName())
                .putExtra(WebViewActivity.INTENT_WEB_URL, data.getContenturl()));
    }

    /**
     * 用户是否注册
     *
     * @param isRegsiter
     */
    @Override
    public void userIsRegister(int isRegsiter) {
        if (isRegsiter == 1) {
            startActivity(new Intent(this, LoginByPwdActivity.class)
                    .putExtra(LoginByPwdActivity.INTENT_TAG_PHONE, etPhone.getText().toString())
                    .putExtra(LoginByPwdActivity.INTENT_TAG_PHONE_CITY, tvPhoneCity.getText().toString()));
        } else {
            startActivity(new Intent(this, SendCodeActivity.class)
                    .putExtra(SendCodeActivity.INTENT_EUNM, SendCodeEnum.LOGIN)
                    .putExtra(SendCodeActivity.INTENT_PHONE_CITY, tvPhoneCity.getText().toString())
                    .putExtra(SendCodeActivity.INTENT_PHONE, etPhone.getText().toString()));
        }
    }

    /**
     * 域名配置获取成功
     *
     * @param data
     */
    @Override
    public void domainNameResult(DomainNameBean data) {
        SPUtils.put(this, Common.DOMAIN_NAME_URL, data.getDomain_url());
    }

    /**
     * 微信登录
     */
    private void wxLogin() {
        //通过WXAPIFactory工厂获取IWXApI的示例
        api = WXAPIFactory.createWXAPI(this, Common.WX_APP_ID, true);
        //将应用的appid注册到微信
        api.registerApp(Common.WX_APP_ID);
        SendAuth.Req req = new SendAuth.Req();
        //授权读取用户信息
        req.scope = "snsapi_userinfo";
        //自定义信息
        req.state = "wechat_sdk_demo_test";
        //向微信发送请求
        boolean isSend = api.sendReq(req);
        if (isSend) {
            showLoading();
        } else {
            showError("微信登录失败");
        }
    }

    /**
     * 微信调用成功
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void wxLoginSuccess(WxLoginSuccessEvent event) {
        if (!event.isSuccess()) {
            hideLoading();
            showError(event.getMsg());
            return;
        }
        LogUtils.d(TAG, event.getCode());
        mPresenter.loginByWx(this, event.getCode(), AppHelper.getDeviceBrand());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
